package com.aiyige.page.publish.selectsuitablepeople;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.request.CreateTagRequest;
import com.aiyige.model.request.GetTagRequest;
import com.aiyige.model.response.CreateTagResponse;
import com.aiyige.model.response.GetTagResponse;
import com.aiyige.model.tag.Tag;
import com.aiyige.page.publish.CommonAddDialog;
import com.aiyige.page.publish.selectcoursetype.model.CourseTypeItem;
import com.aiyige.page.publish.selectlearntarget.SelectLearnTargetPage;
import com.aiyige.page.publish.selectlearntarget.model.SelectLearnTargetItem;
import com.aiyige.page.publish.selectsuitablepeople.adapter.SelectSuitablePeopleAdapter;
import com.aiyige.page.publish.selectsuitablepeople.model.SelectSuitablePeopleItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Route(path = ARouterConfig.SelectSuitablePeoplePage)
public class SelectSuitablePeoplePage extends AppCompatActivity {
    public static final String EXTRA_KEY_SELECTED_SUITABLE_PEOPLE_ID = "com.aiyige.extra.EXTRA_KEY_SELECTED_SUITABLE_PEOPLE_ID";
    public static final String EXTRA_KEY_SELECTED_SUITABLE_PEOPLE_TITLE = "com.aiyige.extra.EXTRA_KEY_SELECTED_SUITABLE_PEOPLE_TITLE";

    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    SelectSuitablePeopleAdapter selectSuitablePeopleAdapter;
    CommonAddDialog commonAddDialog;
    Integer requestGroupId;
    @Autowired
    String channel;
    @Autowired
    SelectSuitablePeopleItem preSelected = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_suitable_people);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (TextUtils.isEmpty(channel)) {
            channel = "";
        }
        titleTv.setText(R.string.select_suitable_people);
        requestGroupId = getResources().getInteger(R.integer.suitable_people_request_group_id);
        commonAddDialog = CommonAddDialog.newInstance(R.string.add_suitable_people, R.string.please_input_suitable_people, 15);
        commonAddDialog.setListener(new CommonAddDialog.Listener() {
            @Override
            public void onOk(String str) {
                doAddSuitablePeople(str);
            }

            @Override
            public void onCancel() {

            }
        });
        selectSuitablePeopleAdapter = new SelectSuitablePeopleAdapter();
        //recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.setLayoutManager(ChipsLayoutManager.newBuilder(this)
                .setChildGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL)
                .build());
        selectSuitablePeopleAdapter.bindToRecyclerView(recyclerView);
        selectSuitablePeopleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SelectSuitablePeopleItem selectSuitablePeopleItem = selectSuitablePeopleAdapter.getItem(position);
                switch (selectSuitablePeopleItem.getType()) {
                    case SelectSuitablePeopleItem.TYPE_ADD:
                        commonAddDialog.show(getSupportFragmentManager(), "");
                        break;
                    case SelectSuitablePeopleItem.TYPE_NORMAL:
                        for (SelectSuitablePeopleItem item : selectSuitablePeopleAdapter.getData()) {
                            item.setSelected(false);
                        }
                        selectSuitablePeopleItem.setSelected(true);
                        selectSuitablePeopleAdapter.notifyDataSetChanged();
                        doSelectSuitablePeople(selectSuitablePeopleItem);
                        break;
                }
            }
        });
        requestData();
    }

    public void restorePreSelected(List<SelectSuitablePeopleItem> selectSuitablePeopleItemList) {
        if (preSelected == null) return;
        for (SelectSuitablePeopleItem item : selectSuitablePeopleItemList) {
            if (preSelected.getId().equals(item.getId())) {
                item.setSelected(true);
                return;
            }
        }
    }

    public void requestData() {
        new RequestDataTask().execute(channel, SetupUtil.GROUP_TYPE_SUITABLE_PEOPLE);
    }

    public void doSelectSuitablePeople(SelectSuitablePeopleItem item) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_KEY_SELECTED_SUITABLE_PEOPLE_ID, item.getId());
        intent.putExtra(EXTRA_KEY_SELECTED_SUITABLE_PEOPLE_TITLE, item.getTitle());
        setResult(RESULT_OK, intent);
        finish();
    }

    public SelectSuitablePeopleItem checkDuplicate(String title) {
        SelectSuitablePeopleItem duplicateItem = null;
        for (SelectSuitablePeopleItem item : selectSuitablePeopleAdapter.getData()) {
            if (item.getTitle().equals(title)) {
                duplicateItem = item;
                break;
            }
        }
        return duplicateItem;
    }

    public void doAddSuitablePeople(String title) {
        SelectSuitablePeopleItem item = checkDuplicate(title);
        if (item != null) {
            doSelectSuitablePeople(item);
            return;
        }
        new CreateUserTagTask().execute(title, channel, SetupUtil.GROUP_TYPE_SUITABLE_PEOPLE);
    }


    @OnClick({R.id.titleBackBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                setResult(RESULT_CANCELED);
                finish();
                break;
        }
    }

    public class RequestDataTask extends AsyncTask<String, Object, Object> {
        LoadingDialog loadingDialog;
        String channel;
        String groupType;
        List<SelectSuitablePeopleItem> selectSuitablePeopleItemList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectSuitablePeoplePage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(String... params) {
            channel = params[0];
            groupType = params[1];
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .getSetup(groupType, BuildConfig.appVersion, channel)
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    List<Setup> setupList = JSON.parseArray(json, Setup.class);
                    for (Setup setup : setupList) {
                        selectSuitablePeopleItemList.add(SelectSuitablePeopleItem.newBuilder()
                                .id(setup.getId())
                                .title((String) setup.getData().get("name"))
                                .build());
                    }
                }
                response = ApiManager.getService()
                        .getUserTag(AccountUtil.getCurrentUser().getId(), channel, groupType)
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    List<Tag> tagList = JSON.parseArray(json, Tag.class);
                    for (Tag tag : tagList) {
                        selectSuitablePeopleItemList.add(SelectSuitablePeopleItem.newBuilder()
                                .id(tag.getId())
                                .title(tag.getName())
                                .build());
                    }
                }
                restorePreSelected(selectSuitablePeopleItemList);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                selectSuitablePeopleItemList.add(SelectSuitablePeopleItem.newBuilder()
                        .type(SelectSuitablePeopleItem.TYPE_ADD)
                        .build());
                selectSuitablePeopleAdapter.setNewData(selectSuitablePeopleItemList);
            }
        }
    }


    public class CreateUserTagTask extends AsyncTask<String, Object, Object> {
        LoadingDialog loadingDialog;
        String tagName;
        String channel;
        String groupType;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectSuitablePeoplePage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(String... strings) {
            tagName = strings[0];
            channel = strings[1];
            groupType = strings[2];
            try {
                Response<ResponseBody> response = ApiManager.getService().createUserTag(Tag.newBuilder()
                        .name(tagName)
                        .channel(channel)
                        .creator(AccountUtil.getCurrentUser().getId())
                        .groupType(groupType)
                        .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    Tag tag = JSON.parseObject(json, Tag.class);
                    return SelectSuitablePeopleItem.newBuilder()
                            .id(tag.getId())
                            .title(tag.getName())
                            .build();
                }
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof SelectSuitablePeopleItem) {
                SelectSuitablePeopleItem item = (SelectSuitablePeopleItem) o;
                doSelectSuitablePeople(item);
            } else if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                ToastX.show(R.string.add_failed);
            }
        }
    }
}
